﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace WindowsServiceTscPrint
{
    /// <summary>
    /// 安装字体
    /// </summary>
    public class InstallFontType
    {
        [DllImport("kernel32.dll", SetLastError = true)]
        static extern int WriteProfileString(string lpszSection, string lpszKeyName, string lpszString);

        //[DllImport("user32.dll")]
        //public static extern int SendMessage(int hWnd, // handle to destination window 
        //uint Msg, // message 
        //int wParam, // first message parameter 
        //int lParam // second message parameter 
        //);

        [DllImport("gdi32")]
        static extern int AddFontResource(string lpFileName);

        /// <summary>
        /// 安装字体
        /// </summary>
        public static void InstallFont()
        {
            try
            {
                string WinFontDir = "C:\\Windows\\Fonts";
                string FontFileName = "GLECB.TTF";
                string FontName = "Gloucester MT Extra Condensed";
                int Ret;
                //int Res;
                //const int WM_FONTCHANGE = 0x001D;
                //const int HWND_BROADCAST = 0xffff;
                string FontPath = WinFontDir + "\\" + FontFileName;
                if (File.Exists(FontPath))
                {
                    LogHelpter.AddLog("存在需要的字体" + FontName);
                }
                else
                {
                    File.Copy(AppDomain.CurrentDomain.BaseDirectory + "\\" + FontFileName, FontPath);
                    Ret = AddFontResource(FontPath);
                    //Res = SendMessage(HWND_BROADCAST, WM_FONTCHANGE, 0, 0);
                    Ret = WriteProfileString("fonts", FontName + "(TrueType)", FontFileName);
                    LogHelpter.AddLog("安装字体成功" + FontPath + ";" + FontName);
                }
            }
            catch (Exception ex)
            {
                LogHelpter.AddLog("安装字体失败，" + ex.Message);
            }
        }
    }
}
